#!/usr/bin/env python
# -*- coding: utf-8 -*-

from requests import post
import datetime
import json

from django.conf import settings

from unitool.redis_model import StringModel


TOKEN = settings.BAIDU_URL_PUSH_TOKEN
URL = "http://data.zz.baidu.com/urls"
HEADERS = {"content_type": "text/plain"}


class BaiduPushUrlApiRemainCache(StringModel):
    def __init__(self):
        # 缓存过期时间
        super().__init__("baidu_api_push_url_remain")

    @property
    def value(self):
        _value = self.json.loads(self.get_value())
        value = _int(value["value"])
        detail_time = _value["detail_time"]
        if (
            datetime.datetime.now().day
            == datetime.datetime.utcfromtimestamp(detail_time).day
        ):
            return value
        return 1

    @value.setter
    def value(self, value):
        data = {
            "value": value,
            "detail_time": datetime.datetime.timestamp(datetime.datetime.now()),
        }
        self.set_value(json.dumps(data))


remain_cache = BaiduPushUrlApiRemainCache()


def push_url(web_host: str, urls: list) -> dict:
    url = "{}?site={}&token={}".format(URL, web_host, TOKEN)
    urls = "\n".join(urls)
    res = post(url, data=urls, headers=HEADERS)
    if res.status_code != 200:
        raise RuntimeError(res.json())
    remain_cache.value = res.json()["remain"]
    return res.json()
